var http = require('../../../utils/https.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    nowDate: Date(),
    date: '2002-08-17',
    fileList: [{
      url: "https://cdn8.axureshop.com/demo/2031830/images/%E9%A6%96%E9%A1%B5/u112.png",
    }, ],
    uploaderConfig: {
      maxCount: 1,
      accept: 'image',
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera']
    }
  },

  // 优化URL验证逻辑：兼容localhost、127.0.0.1和局域网IP
  isValidUrl(url) {
    if (!url) return false;

    // 开发环境特殊处理：直接信任localhost、127.0.0.1和局域网IP
    const devHosts = [
      /^http:\/\/localhost(:\d+)?/,
      /^http:\/\/127\.0\.0\.1(:\d+)?/,
      /^http:\/\/192\.168\.\d+\.\d+(:\d+)?/,
      /^http:\/\/10\.\d+\.\d+\.\d+(:\d+)?/,
      /^http:\/\/172\.(1[6-9]|2\d|3[0-1])\.\d+\.\d+(:\d+)?/
    ];

    for (const hostPattern of devHosts) {
      if (hostPattern.test(url)) {
        return true;
      }
    }

    // 生产环境URL验证
    try {
      new URL(url);
      return true;
    } catch (e) {
      return false;
    }
  },

  // 上传图片处理
  afterRead(event) {
    const http = require('../../../utils/https.js');
    const {
      file
    } = event.detail;

    console.log('上传事件详情:', event);
    console.log('获取到的文件对象:', file);

    // 1. 获取有效的文件路径
    let filePath;
    if (Array.isArray(file)) {
      filePath = file[0]?.path || file[0]?.tempFilePath || file[0]?.tempPath;
    } else {
      filePath = file?.path || file?.tempFilePath || file?.tempPath;
    }

    if (!filePath) {
      wx.showToast({
        title: '获取文件路径失败',
        icon: 'none'
      });
      console.error('无法获取有效的文件路径', file);
      return;
    }
    console.log('最终使用的文件路径:', filePath);

    // 2. 构建并验证上传URL
    if (!http.BASE_URL) {
      wx.showToast({
        title: '服务器配置错误',
        icon: 'none'
      });
      console.error('BASE_URL未配置');
      return;
    }

    // 安全拼接URL
    const uploadPath = 'common/upload';
    let uploadUrl = http.BASE_URL;

    // 处理斜杠问题
    if (uploadUrl && !uploadUrl.endsWith('/') && !uploadPath.startsWith('/')) {
      uploadUrl += '/';
    }
    uploadUrl += uploadPath;

    // 验证URL格式
    const isUrlValid = this.isValidUrl(uploadUrl);
    if (!isUrlValid) {
      wx.showToast({
        title: '上传地址无效',
        icon: 'none'
      });
      console.error('无效的上传URL:', uploadUrl);
      return;
    }
    console.log('使用的上传URL:', uploadUrl);

    wx.showLoading({
      title: '上传中...',
      mask: true
    });

    // 3. 执行上传
    wx.uploadFile({
      url: uploadUrl,
      filePath: filePath,
      name: 'file',
      header: {
        'authorization': wx.getStorageSync('token') || ''
      },
      success: (res) => {
        wx.hideLoading();
        console.log('上传接口返回:', res);

        try {
          const result = JSON.parse(res.data);
          if (res.statusCode === 200 && result.msg == "操作成功") {
            this.setData({
              fileList: [{
                url: result.fileName,
                name: result.fileName
              }]
            });
            wx.showToast({
              title: '上传成功',
              icon: 'success'
            });
            // this.updateUserAvatar(result.url);
          } else {
            wx.showToast({
              title: result.msg || '上传失败',
              icon: 'none'
            });
          }
        } catch (e) {
          console.error('解析返回数据失败', e);
          wx.showToast({
            title: '服务器返回格式错误',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('上传API调用失败:', err);
        wx.showToast({
          title: '上传失败，请重试',
          icon: 'none'
        });
      }
    });
  },

  changeAvater() {
    this.del()
  },
  del() {
    this.setData({
      fileList: []
    })
  },
  show() {
    console.log(this.data.fileList);
  },
  // 设置性别
  onChangeSex(e) {
    this.setData({
      "userInfo.sex": e.detail,
    });
  },

  // 设置生日
  bindDateChange(e) {
    var date = e.detail.value
    this.setData({
      date: date
    })
  },

  // 保存
  yes() {
    // console.log(this.data.userInfo);
    // console.log(this.data.date);
    var userInfo = this.data.userInfo
    var url = this.data.fileList
    console.log(url[0].url);
    userInfo.avatar=url[0].url
    var user = {
      userId: userInfo.userId,
      avatar: url[0].url,
      nickName: userInfo.nickName,
      sex: userInfo.sex,
      birthday: this.data.date
    }
    http.PUT('/system/birthday/updateUserInfo', user, function (res) {
      console.log('修改用户成功:', res);
      if (res.code === 200) {
        wx.setStorageSync('userInfo', userInfo)
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1000
        })
      }
    }, function (err) {
      console.error('失败:', err);
    });


  },
  onNickNameChange(e) {
    const newNickName = e.detail.value;
    this.setData({
      'userInfo.nickName': newNickName
    });
  },

  // 获取用户生日信息
  getBirthday(userId) {
    var that = this
    http.GET(`/system/birthday/getBirthdayByUserId/${userId}`, {}, function (res) {
      console.log('成功:', res);
      if (res.code === 200) {
        that.setData({
          date: res.data.birthday
        })
      }
    }, function (err) {
      console.error('失败:', err);
    });
  },


  onLoad(options) {
    const userInfo = wx.getStorageSync('userInfo') || {}; // 确保userInfo至少是个空对象
    let urlList = [];
    
    // 简化空值判断
    if (!userInfo.avatar) {
      urlList = [{ url: 'https://cdn8.axureshop.com/demo/2031830/images/%E9%A6%96%E9%A1%B5/u112.png' }]; 
    } else {
      urlList = [{ url: userInfo.avatar }];
    }
    
    this.setData({
      userInfo: userInfo,
      fileList: urlList
    });
    
    // 只有当userId存在时才调用接口
    if (userInfo.userId) {
      this.getBirthday(userInfo.userId);
    } else {
      console.log('用户ID不存在');
      // 可以在这里处理用户未登录等情况
    }
  }

})